require "digest/sha1"

class User < ActiveRecord::Base
  
  has_many :products
  
  attr_accessor :password, :password_repeat
  attr_accessible :name, :password, :password_repeat, :level, :first_name, :last_name, :email, :street, :city
  
  validates_presence_of :name, :password, :password_repeat, :level, :first_name, :last_name, :email, :street, :city
  validates_uniqueness_of :name
  
  def before_create
    self.hashed_password = User.hash_password(self.password)
  end
  
  def after_create
    @password = nil
    @password_repeat = nil
  end
  
  def before_update
    self.hashed_password = User.hash_password(self.password)
  end
  
  def after_update
    @password = nil
    @password_repeat = nil
  end
  
  def self.login(name, password)
    hashed_password = hash_password(password || "")
    self.find(:first, :conditions => ["name = ? AND hashed_password = ?", name, hashed_password])
  end

  def try_to_login
    User.login(self.name, self.password)
  end
  
  private #----------------
  
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
  
end
